package com.gxc.controller;

import com.github.pagehelper.PageInfo;
import com.gxc.entity.User;
import com.gxc.mapper.UserMapper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * UserController.
 *
 * @author 宫新程
 * @since 2018/12/28 11:10 AM
 */
@Controller
public class UserController {

  @Resource private UserMapper userMapper;

  /** 分页查询User列表. */
  @GetMapping("/json")
  @ResponseBody
  public PageInfo<User> json(
      @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
      @RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize,
      Model model) {
    if (pageNum < 1) {
      pageNum = 1;
    }
    return new PageInfo<>(userMapper.list(pageNum, pageSize));
  }

  /** 分页查询User列表. */
  @GetMapping("/list")
  public String list(
      @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
      @RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize,
      Model model) {
    if (pageNum < 1) {
      pageNum = 1;
    }
    PageInfo<User> result = new PageInfo<>(userMapper.list(pageNum, pageSize));
    model.addAttribute("data", result);
    return "index";
  }

  /** 批量保存. */
  @PostMapping("/saveAll")
  @ResponseBody
  public Map<String, Object> saveAll(@RequestBody List<User> userList) {
    userMapper.saveAll(userList);
    Map<String, Object> result = new HashMap<>();
    result.put("success", true);
    result.put("list", userList);
    return result;
  }
}
